﻿using System;
using System.Collections;
using System.Xml;
using System.Text;
using InfoJetSoft.Service.Entity;
using InfoJetSoft.Service.Util;

namespace InfoJetSoft.Service.Worker
{
	
	class XSNViewFormatConditionFormatAttributeWorker
	{
		
		public static void  formatConditionFormatAttribute(View view)
		{
			XmlElement root = view.Doc.DocumentElement;
			
			string xdBinding = NamespaceUtil.toFullName(view.XdPrefix, JetConstant.XD_binding);
			
			StringBuilder attributeFilterBuffer = new StringBuilder();
			attributeFilterBuffer.Append("//");
			attributeFilterBuffer.Append(NamespaceUtil.toFullName(view.XslPrefix, "choose"));
			attributeFilterBuffer.Append("/");
			attributeFilterBuffer.Append(NamespaceUtil.toFullName(view.XslPrefix, "when"));
			attributeFilterBuffer.Append("/");
			attributeFilterBuffer.Append(NamespaceUtil.toFullName(view.XslPrefix, "attribute"));
			
			XmlNodeList attributeXmlNodeList = DOMUtil.selectNodes(root, attributeFilterBuffer.ToString(), 0, view.NsResolver);
			foreach (XmlElement attributeElement in attributeXmlNodeList)
			{
				string name = attributeElement.GetAttribute( "name" );
				if( name != null && name.Equals( "contentEditable" ) )
				{
					bool isFalse = false;
					if (attributeElement != null)
					{
						if (attributeElement.InnerText != null && attributeElement.InnerText.Trim().Equals("false"))
						{
							XmlAttribute nameAttr = (XmlAttribute) attributeElement.GetAttributeNode("name");
							nameAttr.Value = "readonly";
							DOMUtil.setNodeValue(attributeElement, "true");
							isFalse = true;
						}
					}
					XmlElement element = XSNViewFormatConditionFormatStyleWorker.findParentHTMLElement(attributeElement);
					if (element != null)
					{
						string binding = element.GetAttribute(xdBinding);
						if (binding == null || binding.Length <= 0)
						{
							element.SetAttribute(xdBinding, JetConstant.URI_XD, ".");
						}
						if( isFalse )
						{
							element.RemoveAttribute( "contentEditable" );
						}
					}
				}
				addConditionFormatTest( view, attributeElement );
			}
		}

		private static void addConditionFormatTest( View view, XmlElement attrElement )
		{
			if( view.Manifest.ConditionFormatTestList == null )
			{
				view.Manifest.ConditionFormatTestList = new ArrayList();
			}
			XmlElement whenElement = (XmlElement)attrElement.ParentNode;
			string test = whenElement.GetAttribute( "test" );
			if( test.Length > 0 )
			{
				view.Manifest.ConditionFormatTestList.Add( test );
			}
		}
		
	}
}